package com.yami.shop.admin.config;


import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yami.shop.common.config.ShopAppContext;
import com.yami.shop.common.model.ShopConfig;
import com.yami.shop.common.util.ShopSysConfiKey;
import com.yami.shop.common.util.ShopSysConfig;
import com.yami.shop.service.ShopConfigService;

import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.DateConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Component
public class StartedEventListener implements ApplicationListener<ContextRefreshedEvent> {

    private static final Logger logger = LoggerFactory.getLogger(StartedEventListener.class);

    @Autowired
    private ShopConfigService shopConfigService;


    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
         ConvertUtils.register(new DateConverter(null), Date.class);
         if(ShopAppContext.getContext() == null){
             ShopAppContext.setApplicationContext(event.getApplicationContext());
             //加载参数配置
             List<ShopConfig> shopConfigsList = shopConfigService.getBaseMapper().selectList(new QueryWrapper<ShopConfig>());
             ShopSysConfig.put(shopConfigsList);
             logger.info("Admin后台加载配置参数：{}",JSONUtil.toJsonStr(shopConfigsList));
             //测试使用
             logger.info("测试参数使用-data：{}", ShopSysConfig.getValue(ShopSysConfiKey.TEST));
             logger.info("StartedEventListener OK");
         }
    }
}
